package com.huatai.model.utils;

import cn.hutool.core.collection.CollectionUtil;
import com.huatai.model.config.TreeNodeConfig;
import com.huatai.model.entity.TreeNodeMap;

import java.util.List;

public class TreeUtil {

    public interface Convert<T,TreeNodeMap>{
        void convert(T object, TreeNodeMap treeNode);
    }

    /**
     * 树构建
     */
    public static <T> List<TreeNodeMap> build(List<T> list, Object parentId, Convert<T,TreeNodeMap> convert){
        return build(list,parentId, TreeNodeConfig.getDefaultConfig(),convert);
    }

    /**
     * 树构建
     */
    public static <T> List<TreeNodeMap> build(List<T> list, Object parentId, TreeNodeConfig treeNodeConfig, Convert<T,TreeNodeMap> convert){
        List<TreeNodeMap> treeNodes = CollectionUtil.newArrayList();
        for(T obj : list){
            TreeNodeMap treeNode = new TreeNodeMap(treeNodeConfig);
            convert.convert(obj,treeNode);
            treeNodes.add(treeNode);
        }

        List<TreeNodeMap> finalTreeNodes = CollectionUtil.newArrayList();
        for(TreeNodeMap treeNode : treeNodes){
            if(parentId.equals(treeNode.getParentId())){
                finalTreeNodes.add(treeNode);
                innerBuild(treeNodes,treeNode);
            }
        }
        return finalTreeNodes;
    }

    private static void innerBuild(List<TreeNodeMap> treeNodes,TreeNodeMap parentNode){
        for(TreeNodeMap childNode : treeNodes){
            if(parentNode.getId().equals(childNode.getParentId())){
                List<TreeNodeMap> children = parentNode.getChildren();
                if(children == null){
                    children = CollectionUtil.newArrayList();
                    parentNode.setChildren(children);
                }
                children.add(childNode);
                childNode.setParentId(parentNode.getId());
                innerBuild(treeNodes,childNode);
            }
        }
    }
}
